package com.abvnet.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP压缩字符串
 * 
 * @author 杜晶
 * @since 2.0
 * 
 */
@Slf4j
public final class GZIPUtils {
	
	public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
	public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";

	/**
	 * 字符串压缩为GZIP字节数组
	 * 
	 * @param str
	 * @return
	 */
	public static byte[] compress(String str) {
		if (str == null || str.length() == 0) {
			return new byte[1];
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		byte[] b = null;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(GZIP_ENCODE_UTF_8));
			gzip.close();
			b = out.toByteArray();
			out.close();
		} catch (IOException e) {
			log.error("gzip compress error.", e);
		}
		return b;
	}

	public static byte[] compress(byte[] bytes) {
		if(bytes == null || bytes.length == 0) {
			return new byte[1];
		}
		byte[] b = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			gzip.write(bytes);
			gzip.finish();
			gzip.close();
			b = out.toByteArray();
			out.close();
		} catch (Exception ex) {
			log.error("gzip compressByte error.", ex);
		}
		return b;
	}

	/**
	 * GZIP解压缩
	 * 
	 * @param bytes
	 * @return
	 */
	public static String uncompress(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return StringUtils.EMPTY;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		try {
			GZIPInputStream gzip = new GZIPInputStream(in);
			byte[] buf = new byte[256];
			int n = -1;
			while ((n = gzip.read(buf)) >= 0) {
				out.write(buf, 0, n);
			}
			byte[] b = out.toByteArray();
			out.flush();
			out.close();
			gzip.close();
			in.close();
			return new String(b, GZIP_ENCODE_UTF_8);
		} catch (IOException e) {
			log.error("gzip uncompress error.", e);
		}
		return StringUtils.EMPTY;
	}

	public static byte[] uncompressByte(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return new byte[1];
		}
		byte[] b = null;
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			GZIPInputStream gzip = new GZIPInputStream(in);
			byte[] buf = new byte[256];
			int n = -1;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			while ((n = gzip.read(buf)) >= 0) {
				out.write(buf, 0, n);
			}
			b = out.toByteArray();
			out.flush();
			out.close();
			gzip.close();
			in.close();
		} catch (Exception ex) {
			log.error("gzip uncompressByte error.", ex);
		}
		return b;
	}
}
